﻿using Microsoft.VisualBasic.FileIO;
using System;
using System.Collections.Generic;
using System.IO;

namespace LauncherUpdate.Units
{
	public static class Common
	{
		public static string FormatByteNum(long num)
		{
			double Dnum = (double)num;
			List<string> list = new List<string> { "B", "KB", "MB", "GB", "TB" };
			int i = 0;
			while ((Dnum > 1024) && (i < 9 - 1))
			{
				Dnum /= 1024;
				i += 1;
			}
			return string.Format("{0:F2}", Dnum) + list[i];
		}

		public static string FormatByteNum(double num)
		{
			List<string> list = new List<string> { "B", "KB", "MB", "GB", "TB" };
			int i = 0;
			while ((num > 1024) && (i < 9 - 1))
			{
				num /= 1024;
				i += 1;
			}
			return string.Format("{0:F2}", num) + list[i];
		}


		public static string FormatTime(int time)
		{
			int m = time / 60;
			int s = time % 60;
			int h = m / 60;
			m %= 60;

			return string.Format("{0:D2}:{1:D2}:{2:D2}", h, m, s);
		}


		public static string GetFileNameFromUrl(string url)
		{
			try
			{
				// 使用 Uri 类来解析 URL
				Uri uri = new Uri(url);

				// 使用 Path.GetFileName 方法来获取文件名
				string fileName = Path.GetFileName(uri.LocalPath);
				return fileName;
			}
			catch (Exception ex)
			{
				Console.WriteLine("Error: " + ex.Message);
				return null;
			}
		}


		public static string GetTempFileName(string fileName)
		{
			return Path.GetFileNameWithoutExtension(fileName) + ".zip_tmp"; ;
		}


		public static bool CheckFileExists(string targetPath, string fileName)
		{
			try
			{
				string filePath = Path.Combine(targetPath, fileName);
				return File.Exists(filePath);
			}
			catch (Exception ex)
			{
				Console.WriteLine("Error: " + ex.Message);
				return false;
			}
		}

		public static string ChangeFileName(string filePath)
		{
			var name = Path.GetFileNameWithoutExtension(filePath);
			var directoryPath = Path.GetDirectoryName(filePath);

			if (File.Exists(filePath))
			{
				string newName= name + ".zip";
				FileSystem.RenameFile(filePath, newName);
				filePath = Path.Combine(directoryPath, newName);
			}
			return filePath ;
		}
		public static long GetHardDiskFreeSpace(string hardDiskName)
		{
			long freeSpace = new long();
			if (!hardDiskName.EndsWith("\\"))
			{
				hardDiskName = hardDiskName + ":\\";
			}
			DriveInfo[] drives = DriveInfo.GetDrives();
			foreach (DriveInfo drive in drives)
			{
				if (drive.Name == hardDiskName)
				{
					freeSpace = drive.TotalFreeSpace;
					break;
				}
			}
			return freeSpace;
		}
	}
}
